import { Component, Input, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { UploadService } from '../../../../services/upload.service';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { NzModalRef } from 'ng-zorro-antd/modal';
import Cropper from 'cropperjs';


@Component({
  selector: 'zepride-upload-header',
  templateUrl: './upload-header.component.html',
  styleUrls: ['./upload-header.component.less']
})


export class UploadHeaderComponent implements OnInit, AfterViewInit {

  constructor(
    public uploadService: UploadService,
    private msg: NzMessageService,
    private modalRef: NzModalRef<UploadHeaderComponent>,

  ) {
  }
  @ViewChild('image') image: ElementRef<HTMLImageElement>;
  @Input() headerImg: string
  base64String = '';
  uploading = false;
  fileList = [];
  type = '';
  croppedImage: any = '';
  cropper: Cropper;

  ngAfterViewInit() {
    this.copper();
  }
  ngOnInit(): void {
    if (!this.headerImg) {
      this.headerImg = '../../../../../assets/images/headerImg.png';
    }
    this.croppedImage = this.headerImg;
    this.base64String = this.headerImg;
  }

  copper() {

    this.cropper = new Cropper(this.image.nativeElement, {
      aspectRatio: 12 / 12,
      movable: true,
      viewMode: 3,
      minCropBoxWidth: 0,
      // 裁剪框最小宽度
      minCropBoxHeight: 0,
      // 裁剪框最小宽度
      minCanvasWidth: 500,
      initialAspectRatio: 0.5,
      autoCropArea: 0.8,

    });
    this.image.nativeElement.addEventListener('cropend', (event) => {
      this.crop();
    });
  }


  beforeUpload = (file: NzUploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    this.type = file.type
    // 文件转化为地址
    this.base64String = window.URL.createObjectURL(file);
    this.cropper.replace(this.base64String);
    return false;
  };

  // 地址转file
  dataURLtoFile(dataURI, type) {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    let fileData = new Blob([new Uint8Array(array)], { type: type });
    let file = new File([fileData], `${new Date().getTime()}.png`, { type: type });
    return file
  }

  // 手动上传文件
  async handleUpload() {
    this.crop();
    let formData = new FormData();
    const file = this.dataURLtoFile(this.croppedImage, this.type)
    formData.append('file', file);
    // console.log(this.fileList, formData);
    this.uploading = true;
    try {
      const { fileUrl } = await this.uploadService.upload(formData)
      this.croppedImage = fileUrl
      this.modalRef.triggerOk()
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
    this.uploading = false
  }

  // 逆时针操作
  anticlockwise() {
    this.cropper.rotate(-90);
  }
  // 顺时针操作
  clockwise() {
    this.cropper.rotate(90);
  }
  // 放大
  big() {
    this.cropper.zoom(0.1)
  }
  // 缩小
  small() {
    this.cropper.zoom(-0.1)
  }

  reset() {
    this.cropper.reset();
  }
  crop() {
    const canvas = this.cropper.getCroppedCanvas();

    this.croppedImage = canvas.toDataURL('image/jpg');
  }
}